<template>
  <div class="common-layout">
    <el-container class="layout-container">
      <el-aside width="220px" class="sidebar">
        <div class="sidebar-content">
          <el-button
            type="primary"
            @click="toCreatePage"
            class="function-btn create-btn"
          >
            <el-icon><Plus /></el-icon>
            新建产品批号
          </el-button>
        </div>
      </el-aside>

      <el-main class="main-content">
        <div class="page-header">
          <h1>批发商企业管理主页</h1>
        </div>

        <el-card class="welcome-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><House /></el-icon>
              <span>欢迎使用批发商企业管理系统</span>
            </div>
          </template>

          <div class="welcome-content">
            <p>请选择左侧的功能按钮开始操作：</p>
            <ul>
              <li>
                <el-icon><Check /></el-icon>
                点击"新建产品批号"进入产品批号创建页面
              </li>
            </ul>
          </div>
        </el-card>

        <!-- 状态筛选 -->
        <div class="filter-section">
          <el-card class="filter-card" shadow="hover">
            <div class="status-filter">
              <el-button
                :type="state === '1' ? 'primary' : ''"
                @click="changeState('1')"
                class="status-btn"
              >
                <el-icon><DocumentAdd /></el-icon>
                新建
              </el-button>
              <el-button
                :type="state === '2' ? 'primary' : ''"
                @click="changeState('2')"
                class="status-btn"
              >
                <el-icon><Clock /></el-icon>
                待确认
              </el-button>
              <el-button
                :type="state === '3' ? 'primary' : ''"
                @click="changeState('3')"
                class="status-btn"
              >
                <el-icon><Check /></el-icon>
                已确认
              </el-button>
              <el-button
                :type="state === '4' ? 'primary' : ''"
                @click="changeState('4')"
                class="status-btn"
              >
                <el-icon><Remove /></el-icon>
                已下架
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 批号列表 -->
        <div class="batch-list">
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>加载中...</span>
          </div>

          <div v-else-if="batchList.length === 0" class="empty-container">
            <el-empty description="暂无数据" />
          </div>

          <div v-else class="batch-cards">
            <el-card
              v-for="batch in batchList"
              :key="batch.wbId"
              class="batch-card"
              shadow="hover"
            >
              <template #header>
                <div class="card-header">
                  <span class="batch-id">批号: {{ batch.batchId }}</span>
                  <el-tag
                    :type="formatStateTag(batch.state)"
                    class="status-tag"
                  >
                    {{ formatState(batch.state) }}
                  </el-tag>
                </div>
              </template>

              <div class="batch-info">
                <div class="info-item">
                  <span class="label">产品类型:</span>
                  <span class="value">{{ batch.productType }}</span>
                </div>
                <div class="info-item">
                  <span class="label">品种:</span>
                  <span class="value">{{ batch.productVariety }}</span>
                </div>
                <div class="info-item">
                  <span class="label">屠宰企业:</span>
                  <span class="value">{{ batch.slauEntName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">上游批号:</span>
                  <span class="value">{{ batch.slauBatchId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间:</span>
                  <span class="value">{{ batch.createTime }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="action-buttons">
                <!-- 新建状态：更新、删除、发送确认 -->
                <template v-if="batch.state === 1">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleUpdate(batch)"
                    class="action-btn"
                  >
                    <el-icon><Edit /></el-icon>
                    更新
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(batch.wbId)"
                    class="action-btn"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                  <el-button
                    type="success"
                    size="small"
                    @click="handleSendConfirm(batch.wbId)"
                    class="action-btn"
                  >
                    <el-icon><Position /></el-icon>
                    发送确认
                  </el-button>
                </template>

                <!-- 已确认状态：下架 -->
                <template v-else-if="batch.state === 3">
                  <el-button
                    type="warning"
                    size="small"
                    @click="handleOffline(batch.wbId)"
                    class="action-btn"
                  >
                    <el-icon><Remove /></el-icon>
                    下架
                  </el-button>
                </template>

                <!-- 所有状态：详情 -->
                <el-button
                  type="info"
                  size="small"
                  @click="toDetailPage(batch.wbId)"
                  class="action-btn"
                >
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          :current-page="pageInfo.pageNum"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next"
          style="margin-top: 30px; text-align: right;"
          :disabled="loading"
          background
        />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  House,
  Check,
  DocumentAdd,
  Clock,
  Remove,
  Loading,
  Edit,
  Delete,
  Position,
  View
} from '@element-plus/icons-vue'
import { 
  getWholBatchPageService, 
  deleteWholBatchService,
  sendConfirmService,
  offlineWholBatchService
} from '@/api/wholesaler'

const router = useRouter()
const state = ref('1') // 默认显示"新建"状态
const loading = ref(false) // 加载状态

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 批号列表数据
const batchList = ref([])

// 格式化状态显示
const formatState = (state) => {
  const stateMap = {
    1: '新建',
    2: '待确认',
    3: '已确认',
    4: '已下架'
  }
  return stateMap[state] || '未知'
}

// 格式化状态标签类型
const formatStateTag = (state) => {
  const typeMap = {
    1: 'primary',
    2: 'warning',
    3: 'success',
    4: 'info'
  }
  return typeMap[state] || 'info'
}

// 加载列表数据
const loadBatchList = async () => {
  loading.value = true
  try {
    const res = await getWholBatchPageService({
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      state: state.value
    })
    
    batchList.value = res.data.records || []
    pageInfo.value.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败: ' + (error.message || '未知错误'))
    batchList.value = []
    pageInfo.value.total = 0
  } finally {
    loading.value = false
  }
}

// 状态切换
const changeState = (newState) => {
  state.value = newState
  pageInfo.value.pageNum = 1
  loadBatchList()
}

// 分页变化
const handlePageChange = (pageNum) => {
  pageInfo.value.pageNum = pageNum
  loadBatchList()
}

const handleSizeChange = (pageSize) => {
  pageInfo.value.pageSize = pageSize
  pageInfo.value.pageNum = 1
  loadBatchList()
}

// 跳转到创建页面
const toCreatePage = () => {
  router.push('/wholesaler/batch/create')
}

// 跳转到详情页面
const toDetailPage = (id) => {
  router.push(`/wholesaler/batch/detail/${id}`)
}

// 处理更新
const handleUpdate = (row) => {
  router.push(`/wholesaler/batch/update/${row.wbId}`)
}

// 处理删除
const handleDelete = async (id) => {
  ElMessageBox.confirm(
    '确定要删除该批号吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteWholBatchService(id)
      ElMessage.success('删除成功')
      loadBatchList()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  })
}

// 发送确认请求
const handleSendConfirm = async (id) => {
  try {
    await sendConfirmService(id)
    ElMessage.success('已发送确认请求')
    loadBatchList()
  } catch (error) {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'))
  }
}

// 下架处理
const handleOffline = async (id) => {
  try {
    await offlineWholBatchService(id)
    ElMessage.success('已下架')
    loadBatchList()
  } catch (error) {
    ElMessage.error('下架失败: ' + (error.message || '未知错误'))
  }
}

// 初始化
onMounted(() => {
  loadBatchList()
})
</script>

<style scoped>
.common-layout {
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.layout-container {
  height: 100%;
}

.sidebar {
  background: linear-gradient(180deg, #2d3748 0%, #1a202c 100%);
  padding: 20px;
  display: flex;
  align-items: flex-start;
}

.sidebar-content {
  width: 100%;
}

.function-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 16px;
  margin: 0 !important;
}

.create-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
}

.function-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.function-btn .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.main-content {
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 600;
}

.welcome-card {
  max-width: 600px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.welcome-content {
  line-height: 1.6;
  color: #4a5568;
}

.welcome-content p {
  margin-bottom: 16px;
  font-size: 15px;
}

.welcome-content ul {
  margin: 0;
  padding-left: 0;
  list-style: none;
}

.welcome-content li {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.welcome-content li:hover {
  background: #ecf5ff;
  transform: translateX(5px);
}

.welcome-content li .el-icon {
  margin-right: 8px;
  color: #67c23a;
  font-size: 14px;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
}

.status-filter {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.status-btn {
  border-radius: 8px;
  height: 40px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

.status-btn:hover {
  transform: translateY(-2px);
}

.status-btn .el-icon {
  margin-right: 6px;
}

.batch-list {
  min-height: 400px;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #718096;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.batch-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.batch-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s ease;
}

.batch-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-id {
  font-weight: 600;
  color: #2d3748;
}

.status-tag {
  font-weight: 500;
}

.batch-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 4px 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #718096;
  font-size: 14px;
  font-weight: 500;
}

.value {
  color: #2d3748;
  font-size: 14px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.action-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

.action-btn .el-icon {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    height: auto;
  }

  .main-content {
    padding: 20px;
  }

  .page-header h1 {
    font-size: 24px;
  }

  .status-filter {
    flex-direction: column;
  }

  .status-btn {
    width: 100%;
  }

  .batch-cards {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .action-buttons {
    justify-content: center;
  }
}
</style>